package org.mobile.api;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mobile.model.util.Constants;
import org.mobile.model.util.ServiceUtil;
import org.mobile.model.util.WebUtil;
import org.springframework.data.redis.core.RedisTemplate;


/**
 * @author sbwkl
 * 转发到isv用api
 */
public class IsvApi implements Api {

    private static final Logger LOG = Logger.getLogger(IsvApi.class);

    private static final String[] FILTER_PARAMS = { "identity", "user_id",
            "hospitalId", "user_type", "app_key", "app_id", "api_name",
            "userId", "session_id", "session_id", "client_session" };

    private MemcachedClient memcachedClient;
    
//    private RedisTemplate redisTemplate;

    public void setMemcachedClient(MemcachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }
    
//    public void setRedisTemplate(RedisTemplate redisTemplate) {
//		this.redisTemplate = redisTemplate;
//	}



	@Override
    public JSONObject execute(JSONObject params) {
        JSONObject res = new JSONObject();
        Integer hid = params.optInt("hospitalId");
        String apiName = params.optString("api_name");
        JSONObject config = getHospitalConfig(hid);
        if(StringUtils.isBlank(config.optString("gateway"))) {
            res.put("ret_code", 3);
            res.put("ret_info", "该服务暂不可用");
            res.put("info", "未设置开发者网关");
            return res;
        }
        JSONObject p = new JSONObject();
        p.put("appApiName", apiName);
        JSONObject in = ServiceUtil.doService("processInterfaceService",
                "getInterfaceByApi", p);
        JSONArray list = getAdminFunctions(hid);
        if(list == null) {
            res.put("ret_code", 3);
            res.put("ret_info", "该服务暂不可用");
            res.put("info", "商户未开通该功能");
            return res;
        }
        Set<Integer> set = new HashSet<Integer>();
        for(Object o : list) {
            JSONObject tmp = (JSONObject) o;
            set.add(tmp.optInt("processId"));
        }
        if(!set.contains(in.optInt("processId"))) {
            res.put("ret_code", 3);
            res.put("ret_info", "该服务暂不可用");
            res.put("info", "商户未开通该功能");
            return res;
        }
        String sessionId = params.optString("session_id");
        //String login = in.optString("login");
        //if("1".equals(login) && StringUtils.isBlank(sessionId)) {
            try {
                JSONObject d = memcachedClient.get(Constants.ZSHT_DOCTOR
                        + sessionId);
                if(d != null) {
                    String uuid = UUID.randomUUID().toString();
                    memcachedClient.add(uuid, 30 * 60, sessionId);
                    params.put("auto_code", uuid);
                    params.put("login_name", d.optString("login_name"));
                    params.put("doctor_number", d.optString("login_name"));
                }
            } catch(TimeoutException e1) {
                e1.printStackTrace();
            } catch(InterruptedException e1) {
                e1.printStackTrace();
            } catch(MemcachedException e1) {
                e1.printStackTrace();
            }
        //}
        String rsp = null;
        try {
            LOG.info("post request to : " + config.optString("gateway"));
            Map<String, String> m = filterParams(params, in);
            rsp = WebUtil.doPost(config.optString("gateway"),
                    m, 20 * 1000, 20 * 1000);
            for (String k : m.keySet()) {
                LOG.info("params :" + k + " --> " + m.get(k));
            }
        } catch(IOException e) {
            LOG.error("", e);
        }
        if(rsp == null) {
            res.put("ret_code", 1);
            res.put("ret_info", "服务器繁忙，请稍候再试");
            return res;
        }
        res.put("ret_code", 0);
        res.put("ret_info", "");
        // TODO 校验返回参数是否满足文档

        try {
            res = JSONObject.fromObject(rsp);
        } catch(Exception e) {
            res.put("ret_code", 4);
            res.put("ret_info", "返回数据不符合文档");
            return res;
        }
        return res;
    }

    private JSONObject getHospitalConfig(Integer hid) {
        JSONObject p = new JSONObject();
        p.put("hid", hid);
        JSONObject res = ServiceUtil.doService("adminConfigService",
                "getAdminConfigByHid", p);
        return res;
    }

    private JSONArray getAdminFunctions(Integer hid) {
        JSONObject p = new JSONObject();
        p.put("hid", hid);
        p.put("pageNo", 1);
        p.put("pageSize", Integer.MAX_VALUE);
        JSONObject res = ServiceUtil.doService("adminFunctionService",
                "getAdminFunctionByHid", p);
        return res.optJSONArray("list");
    }

    @SuppressWarnings("unchecked")
    private Map<String, String> filterParams(JSONObject params,
            JSONObject in) {
        Map<String, String> map = new HashMap<String, String>();
        Iterator<String> it = params.keys();
        while(it.hasNext()) {
            String key = it.next();
            if(Arrays.asList(FILTER_PARAMS).contains(key)) {
                continue;
            }
            map.put(key, params.optString(key));
        }
        map.put("service", in.optString("isvApiName"));
        return map;
    }
}
